import cv2
import numpy as np
from PIL import Image  # Image Processing
import easyocr


def main():
    harcascade = "haarcascade_russian_plate_number.xml"
    min_area = 500
    count = 0

    # Replace the file uploader with a file path
    file_path = "img.png"  # Replace with your file path

    # Read the image file
    img = cv2.imread(file_path)

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    plate_cascade = cv2.CascadeClassifier(harcascade)
    plates = plate_cascade.detectMultiScale(img_gray, 1.1, 4)

    for (x, y, w, h) in plates:
        area = w * h

        if area > min_area:
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(img, "Number Plate", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255, 0, 255), 2)

            img_roi = img[y: y + h, x: x + w]

            # Check if img_roi is not empty
            if img_roi.size == 0:
                print("No license plate detected in the image.")
                continue

            # Save the cropped and annotated image
            cv2.imwrite("plate_0.jpg", img_roi)

            count += 1
            image = Image.open('plate_0.jpg')

            reader = easyocr.Reader(['en'])
            img = cv2.imread('plate_0.jpg')
            result = reader.readtext(img)

            # Print the result to the console
            print("Extracted Text: " + result[0][-2].upper())


if __name__ == '__main__':
    main()
